package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.UtilFuns;
import com.itheima.doamin.cargo.ContractProduct;
import com.itheima.doamin.cargo.ContractProductExample;
import com.itheima.doamin.cargo.Factory;
import com.itheima.doamin.cargo.FactoryExample;
import com.itheima.service.cargo.ContractProductService;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import com.itheima.web.utils.FileUploadUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 货物
 */
@Controller
@RequestMapping("cargo/contractProduct")
public class ContractProductController extends BaseController{
    @Reference
    ContractProductService contractProductService;
    @Reference
    FactoryService factoryService;
    @Autowired
    FileUploadUtil fileUploadUtil;

    @RequestMapping("list")
    public String list(String contractId,@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "2")int size){
        //查询条件
        ContractProductExample contractProductExample=new ContractProductExample();
        contractProductExample.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(contractProductExample, page, size);
        request.setAttribute("page",pageInfo);
        //对货物id存入request域
        request.setAttribute("contractId",contractId);
        //查询工厂
        //条件对象
        FactoryExample factoryExample=new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> list=factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",list);
        return "cargo/product/product-list";
    }

    //添加或者更新
    @RequestMapping("edit")
    public String toEdit(ContractProduct contractProduct, MultipartFile productPhoto) throws Exception {
        if (UtilFuns.isEmpty(contractProduct.getId())){
            //保存
            contractProduct.setCompanyId(super.getCurrentUser().getCompanyId());
            contractProduct.setCompanyName(super.getCurrentUser().getCompanyName());
            String proPhoto="";
            if (productPhoto !=null){
                proPhoto ="http://"+fileUploadUtil.upload(productPhoto);
            }
            contractProduct.setProductImage(proPhoto);
            contractProductService.save(contractProduct);
        }else {
            String proPhoto="";
            if (productPhoto !=null){
                proPhoto ="http://"+fileUploadUtil.upload(productPhoto);
            }
            contractProduct.setProductImage(proPhoto);
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list?contractId="+contractProduct.getContractId();
    }

    //删除货物
    @RequestMapping("delete")
    public String delete(String id){
        //根据id查询对应的货物获得合同信息
        ContractProduct contractProduct = contractProductService.findById(id);
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId="+contractProduct.getContractId();
    }

    @RequestMapping("toUpdate")
    public String toUpdate(String id){
        //货物的回显
        ContractProduct contractProduct=new ContractProduct();
        contractProduct=contractProductService.findById(id);

        //工厂列表回显
        //条件对象
        FactoryExample factoryExample=new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        //开始查询
        List<Factory> factories = factoryService.findAll(factoryExample);
        //将查询到的数据存入request域中
        request.setAttribute("contractProduct",contractProduct);
        request.setAttribute("factoryList",factories);
        return "cargo/product/product-update";
    }

    //上传货物
    @RequestMapping("toImport")
    public String toImport(String contractId){
        //进行跳转到上床货物页面
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    //上传货物实现
    @RequestMapping("import")
    public String importImp(String contractId,MultipartFile file) throws Exception {
        //创建list集合
        List<ContractProduct> contractProducts=new ArrayList<>();
        //创建excel表对象
        Workbook workbook=new XSSFWorkbook(file.getInputStream());
        //创建工作簿对象
        Sheet sheet1 = workbook.getSheetAt(0);
        //循环读取数据
        //创建数组封装数据
        Object[] objArr=new Object[10];
        for (int i=1;i<=sheet1.getLastRowNum();i++){
            //获得行
            Row row = sheet1.getRow(i);
            //根据行获得行中的每一列
            for (int j=0;j<row.getLastCellNum();j++){
                //获得每一列
                Cell cell = row.getCell(j);
                //获取值
                objArr[j]=getCellValueByCellType(cell);
            }
            //创建货物对象
            ContractProduct contractProduct=new ContractProduct
                    (objArr,getCurrentUser().getCompanyId(),getCurrentUser().getCompanyName());
            contractProduct.setContractId(contractId);
            contractProducts.add(contractProduct);
        }

        //调用service层将数据保存
        contractProductService.findAllByList(contractProducts);
        return "redirect:/cargo/contractProduct/list?contractId="+contractId;
    }


    /**
     * 用于判断单元格的返回值
     * @param cell
     * @return
     */
    private Object getCellValueByCellType(Cell cell) {
        if (cell!=null){
            switch (cell.getCellType()){
                case STRING:
                    return cell.getStringCellValue();
                case BOOLEAN:
                    return cell.getBooleanCellValue();
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)){
                        return cell.getDateCellValue();
                    }else {
                        return cell.getNumericCellValue();
                    }
            }
        }
        return null;
    }

}